<template>
  <el-form :inline="true">
    <el-form-item>
      <el-button type="primary" icon="Plus" @click="addDialog = true">添加员工</el-button>
      <el-button type="danger" icon="Delete" @click="deleteStaff(multipleSelection)">批量删除</el-button>
      <el-link href="https://blb-manage.oss-cn-wuhan-lr.aliyuncs.com/%E7%94%A8%E6%88%B7%E6%A8%A1%E6%9D%BF.xlsx">
        <el-button icon="Download" type="primary" plain>模板下载</el-button>
      </el-link>
      <el-upload class="upload-demo" action="/excelUpload" :on-success="handleSuccess" :on-error="handleError"
        :before-upload="beforeUpload" :show-file-list="false" accept=".xlsx,.xls">
        <el-button type="primary" icon="Edit" plain>导入员工</el-button>
      </el-upload>
      <el-button type="primary" style="margin-left: 15px" icon="Upload" @click="exportStaff" plain>导出员工</el-button>
    </el-form-item>
  </el-form>

  <!-- 模糊查询开始 -->
  <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="工号: ">
      <el-input v-model="formInline.staffNo" placeholder="请输入工号" clearable />
    </el-form-item>
    <el-form-item label="姓名:">
      <el-input v-model="formInline.realName" placeholder="请输入姓名" clearable />
    </el-form-item>
    <el-form-item label="组织:">
      <el-tree-select v-model="formInline.organizationId" :data="organizationList" :props="defaultProps" node-key="id"
        check-strictly :render-after-expand="false" clearable style="width: 240px" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">搜索</el-button>
      <el-button @click="reset">清空</el-button>
    </el-form-item>
  </el-form>
  <!-- 模糊查询结束 -->

  <!-- 列表渲染开始 -->
  <el-table ref="multipleTableRef" border v-loading="loading" style="width: 100%" :data="tableData"
    @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" align="center" />
    <el-table-column label="头像" align="center">
      <template v-slot="scope">
        <div class="block">
          <el-avatar shape="square" :size="30" :src="tableData[scope.$index].photoUrl" />
        </div>
      </template>
    </el-table-column>
    <el-table-column property="staffNo" width="80" label="工号" align="center" />
    <el-table-column property="realName" label="姓名" width="90" align="center" />
    <el-table-column property="idCard" label="身份证号" min-width="173" align="center" />
    <el-table-column property="phone" label="手机号" width="117" align="center" />
    <el-table-column property="organizationName" label="组织名称" min-width="193" align="center" />
    <el-table-column property="jobName" label="岗位名称" width="100" align="center" />
    <el-table-column property="salary" label="薪资(RMB)" width="100" align="center" />
    <el-table-column property="joinDate" label="入职日期" width="110" align="center" />
    <el-table-column property="leaveDate" label="离职日期" width="110" align="center" />
    <el-table-column label="状态" fixed="right" width="70" align="center">
      <template v-slot="scope">
        <el-switch size="small" v-model="scope.row.status"
          @click="updateStatus(scope.$index, scope.row.id, scope.row.status)" />
      </template>
    </el-table-column>
    <el-table-column label="操作" fixed="right" width="330" align="center">
      <template v-slot="scope">
        <el-link type="primary" icon="edit" style="margin-right: 10px" @click="showUpdate(scope.row)">修改</el-link>
        <el-link type="primary" icon="delete" style="margin-right: 10px" @click="deleteStaff(scope.row.id)">删除</el-link>
        <el-link type="primary" icon="paperclip" style="margin-right: 10px"
          @click="getRoleById(scope.row.id)">关联角色</el-link>
        <el-link type="primary" icon="paperclip" @click="getSubjectById(scope.row.id)">关联学科</el-link>
      </template>
    </el-table-column>
  </el-table>
  <div class="demo-pagination-block" style="margin-top: 20px">
    <el-pagination size="small" v-model:current-page="page" v-model:page-size="size" :page-sizes="[5, 10, 15, 20]"
      :total="total" :background="true" layout="total, sizes, prev, pager, next" @current-change="handleCurrentChange"
      @size-change="handleSizeChange" />
  </div>
  <!-- 列表渲染结束 -->

  <!--员工添加-->
  <StaffAdd v-model:addDialog="addDialog" @loadData="selectAll(page, size)" />
  <!--修改弹框界面-->
  <saffUpdate v-if="updateDialog" v-model:updateDialog="updateDialog" @updateList="selectAll" :rowData="rowData" />
  <!-- 关联角色 -->
  <RelevancyStaff v-model:relevancyStaffDialog="relevancyStaffDialog" :roleNameList="roleNameList"
    :currentID="currentID" :formData="formData" />
  <!--关联学科-->
  <StaffSubject v-model:subjectDialog="subjectDialog" :subjectNameList="subjectNameList" :empId="empId"
    :formData="formData" />

</template>

<script setup>
import { ref, onMounted, reactive } from "vue"
import axios from "@/axios/index.js"
import { ElMessageBox, ElMessage, ElTable, ElDialog } from "element-plus"
import StaffAdd from "./StaffAdd.vue"
import saffUpdate from "./SaffUpdate.vue"
import RelevancyStaff from "./RelevancyStaff.vue"
import StaffSubject from "@/views/system/staff/StaffSubject.vue"

const loading = ref(true)
const multipleTableRef = ref()
const multipleSelection = ref([])
const organizationList = ref([]) //组织列表
const tableData = ref([])
const page = ref(1) //当前页
const size = ref(5) //每页显示条数
const total = ref(100) //总记录数
const defaultProps = {
  label: "organizationName",
}
//模糊搜索表单
const formInline = ref({
  staffNo: "",
  realName: "",
  organizationId: "",
})

let addDialog = ref(false)
//关联角色
let relevancyStaffDialog = ref(false)
//关联学科弹窗
let subjectDialog = ref(false)

//职位集合
let roleNameList = ref([])
//学科集合
let subjectNameList = ref([])

//已经选中角色
let formData = reactive({
  roleNameList: [],
  subjectNameList: []
})

let updateDialog = ref(false)
let rowData = reactive({})

//当前员工id
let currentID = ref()
//学科关联的员工id
let empId = ref()

//导出用户
const exportStaff = async () => {
  try {
    const response = await axios.get('/staff/downloadStaffs', {
      responseType: 'blob',
      headers: {
        'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      },
    })
    // 创建一个临时的 URL 对象，用于下载文件
    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    // 根据后端设置的文件名格式推测文件名
    const fileNameRegex = /users_\d+\.xlsx/
    const fileName = response.headers['content-disposition'].match(fileNameRegex)[0]
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
    // 清理临时 URL 对象
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('导出用户失败：', error)
  }
}

const handleSuccess = (response, file, fileList) => {
  ElMessage.success(response)
}

const handleError = (err, file, fileList) => {
  ElMessage.error(err.response.data)
}

const beforeUpload = (file) => {
  const isExcel = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  if (!isExcel) {
    ElMessage.error('请上传Excel文件')
    return false
  }
  const formData = new FormData()
  formData.append('file', file)
  axios.post('/staff/excelUpload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then((res) => {
    handleSuccess(res.data, file, [])
    selectAll(page.value, size.value)
  }).catch((err) => {
    handleError(err, file, [])
  })
  return false
}

//根据员工id获取旗下公司职位
let getRoleById = function (id) {
  currentID.value = id
  axios.get("/role/getRoleById", {
    params: {
      roleId: id,
    },
  })
    .then((res) => {
      roleNameList.value = []
      let data = res.data.data
      for (let i = 0; i < data.length; i++) {
        roleNameList.value.push({
          roleId: data[i].id,
          roleName: data[i].roleName,
        })
      }

      relevancyStaffDialog.value = true
    })

  //获取员工已经存在的角色
  axios.get("/staffRole/getRoleById/" + id).then((resp) => {
    formData.roleNameList = []
    let data = resp.data.data
    for (let i = 0; i < data.length; i++) {
      formData.roleNameList.push(data[i].roleId)
    }
  })
}

//获取所有学科
let getSubjectById = function (id) {
  empId.value = id
  axios.get(`/api/v1/admin/subject/getSubjectById`, {
    params: {
      subjectId: id,
    },
  }).then(resp => {
    subjectNameList.value = resp.data.data
    subjectDialog.value = true
  })

  //通过员工id获取已有的学科信息
  axios.get(`/api/v1/admin/subject/getSubjectByStaffId`, {
    params: {
      empId: id
    }
  }).then(resp => {
    formData.subjectNameList = []
    let data = resp.data.data
    for (let i = 0; i < data.length; i++) {
      formData.subjectNameList.push(data[i].id)
    }
  })
}

//显示修改界面
function showUpdate(rowData1) {
  rowData = rowData1
  updateDialog.value = true
}

//删除用户
let deleteStaff = function (id) {
  let ids = ref([])

  if (typeof id == "number") {
    ids.value.push(id)
  } else {
    for (let i = 0; i < id.length; i++) {
      ids.value.push(id[i].id)
    }
  }
  if (ids.value.length < 1) {
    ElMessageBox.alert('请选择至少一条数据', '系统提示', {
      confirmButtonText: '好的',
      type: 'warning'
    }).catch(() => { })
    return
  }
  ElMessageBox.confirm("该操作将永久删除数据,请确认是否继续操作?", "系统提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    axios.get(`/staff/deleteStaff/${ids.value}`).then((response) => {
      ElMessage({
        type: "success",
        message: "删除成功",
      })
      selectAll(page.value, size.value)
    })
  }).catch(() => { })
}

//修改状态
let updateStatus = function (index, id, status) {
  ElMessageBox.confirm("该操作将修改当前用户状态,请确认是否继续操作?", "系统提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    if (status) {
      status = 1
    } else {
      status = 0
    }
    axios.get(`/staff/updateStatus`, {
      params: {
        id,
        status,
      },
    }).then((response) => {
      selectAll(page.value, size.value)
    })
  }).catch(() => {
    tableData.value[index].status = !status
  })
}

//模糊搜索
const onSubmit = function () {
  axios
    .post(
      `/staff/selectAll?current=${page.value}&size=${size.value}`,
      formInline.value
    )
    .then(response => {
      console.log(response)
      tableData.value = []
      //循环遍历数组,将获取到的数组中的staff对象添加到数组中,并将组织名称添加到数组
      for (let i = 0; i < response.data.data.data.length; i++) {
        if (response.data.data.data[i].staff.status == 1) {
          response.data.data.data[i].staff.status = true
        } else {
          response.data.data.data[i].staff.status = false
        }
        tableData.value.push(response.data.data.data[i].staff)
        tableData.value[i].organizationName =
          response.data.data.data[i].organizationName
      }
      //给总条数赋值
      total.value = response.data.data.total
      loading.value = false
    })
}

let reset = function () {
  formInline.value = {
    staffNo: "",
    realName: "",
    organizationId: "",
  }
  onSubmit()
}

//获取用户列表
let selectAll = function (current, limit) {
  page.value = current
  size.value = limit
  tableData.value = []
  axios
    .post(`/staff/selectAll?current=${current}&size=${limit}`, formInline.value)
    .then((response) => {
      //循环遍历数组,将获取到的数组中的staff对象添加到数组中,并将组织名称添加到数组
      for (let i = 0; i < response.data.data.data.length; i++) {
        if (response.data.data.data[i].staff.status == 1) {
          response.data.data.data[i].staff.status = true
        } else {
          response.data.data.data[i].staff.status = false
        }
        if (response.data.data.data[i].staff.photoUrl == null) {
          response.data.data.data[i].staff.photoUrl = 'https://blb-manage.oss-cn-wuhan-lr.aliyuncs.com/8571825f-b7cd-45ec-ba44-f15accb471bc.png'
        }
        tableData.value.push(response.data.data.data[i].staff)
        tableData.value[i].organizationName = response.data.data.data[i].organizationName
      }
      //给总条数赋值
      total.value = response.data.data.total
      loading.value = false
    })
}

//获取组织列表
let selectOrganizationList = function () {
  axios.get(`/organization/getList`).then((response) => {
    let result = response.data.data
    organizationList.value = result
  })
}

//页面渲染时获取用户列表
onMounted(() => {
  selectAll(page.value, size.value)
  selectOrganizationList()
})

//多选框发生变化
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

//page发生变化触发
const handleCurrentChange = (val) => {
  selectAll(val, size.value)
}

const handleSizeChange = (val) => {
  selectAll(page.value, val)
}

</script>

<style lang="less" scoped>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.el-link {
  margin-left: 15px;
  margin-right: 15px;
}

.el-link::after {
  display: none;
}
</style>
